<?php

class home extends WebService {

    const MAX_TOP_VIDEOS_SIZE = 10;
    
    /**
     * actionDefault
     * @todo Tra ve random video theo tung ngay
    */  
    public function actionDefault() {
        import("database");
        /* ========================  TOP VIDEOS  ====================== */
            $top_new_video = array();
            if(!isset($_GET['page'])){
               $page = 1;
            }else{
               $page = $_GET['page'];
            }
            if(!is_numeric($page)){
               die('argument $page is not numberic');
            }else{
               $sql_query = "SELECT 
                               vid_id as vid,
                               vid_image as image,
                               vid_name as title,
                               vid_id_youtube as link,
                               vid_view as view,
                               vid_duration as duration 
                            FROM  
                                  video 
                            WHERE
                                  vid_active = 1      
                            ORDER BY 
                                  RAND() 
                            LIMIT " . ($page - 1) * self::MAX_TOP_VIDEOS_SIZE . "," . self::MAX_TOP_VIDEOS_SIZE;
      
      
              $db_access = new db_query($sql_query);
              while ($row = mysql_fetch_assoc($db_access->result)) {
                  $top_new_video[] = $row;
              }
              if(count($top_new_video) > 0){
                  $status_code = 1;
                  $message =  'Thành công';
              }
              mysql_free_result($db_access->result);
              unset($db_access);    
            }         
        

        /* ======================== RESPONSE  ================ */
        $response = new RequestResponse();
        $response->setBodyJSON(array("videos" => $top_new_video));
        $response->process();
    }
    
   /**
    * 
    * actionHot
    * @param int limit video
    * @param int paging
   */ 
   public function actionHot(){
      import("database");
      /*============== TOP VIDEO HOT ===============*/
      $page = isset($_GET['page']) ? $_GET['page'] : 1;
      $limit = $page - 1 . ', 8';  
      $sql_query = "SELECT 
                         vid_id as vid,
                         vid_image as image,
                         vid_name as title,
                         vid_id_youtube as link,
                         vid_view as view,
                         vid_duration as duration 
                      FROM  
                            video 
                      WHERE
                            vid_active = 1
                      AND
                            vid_hot = 1      
                      ORDER BY 
                            vid_view DESC 
                      LIMIT " . $limit;
      $db_access = new db_query($sql_query);
      $top_new_video = array();
      while ($row = mysql_fetch_assoc($db_access->result)) {
         $top_new_video[] = $row;
      }
      mysql_free_result($db_access->result);
      unset($db_access); 
        
      
      /* ======================== RESPONSE  ================ */
      $response = new RequestResponse();
      $response->setBodyJSON(array("videos" => $top_new_video));
      $response->process();
      
   }
   
   /**
     * actionView
     * @todo Tra ve danh sach video co luong view cao nhat
    */  
   public function actionView(){
      import("database");
      /* ========================  TOP VIDEOS  ====================== */  
        
            $sql_query = "SELECT 
                            vid_id as vid,
                            vid_image as image,
                            vid_name as title,
                            vid_id_youtube as link,
                            vid_view as view,
                            vid_duration as duration 
                         FROM  
                               video 
                         WHERE
                               vid_active = 1      
                         ORDER BY 
                               vid_view DESC 
                         LIMIT " . self::MAX_TOP_VIDEOS_SIZE;
   
   
           $db_access = new db_query($sql_query);
           $top_new_video = array();
           while ($row = mysql_fetch_assoc($db_access->result)) {
               $top_new_video[] = $row;
           }
           mysql_free_result($db_access->result);
           unset($db_access); 
        

        /* ======================== RESPONSE  ================ */
        $response = new RequestResponse();
        $response->setBodyJSON(array("videos" => $top_new_video));
        $response->process();
      
   }
   
   /**
     * actionView
     * @todo Tra ve danh sach video theo ten ca si
    */  
   public function actionPerson(){
      import("database");
       if(!isset($_GET['pname'])){
         $reponse = new RequestResponse(400, "Missing 'pname' arguments");
         $reponse->process();
      }else{
         $pName = $_GET['pname'];
      } 
      /* ========================  LIST VIDEOS  ====================== */
            $status_code   = 0;
            $message       = 'Hết dữ liệu';
            $sql_query = "SELECT 
                            video.vid_id as vid,
                            vid_image as image,
                            vid_name as title,
                            vid_id_youtube as link,
                            vid_view as view,
                            vid_duration as duration 
                         FROM  
                               video
                         INNER JOIN 
                               vid_per
                         ON 
                               video.vid_id = vid_per.vid_id    
                         INNER JOIN
                               person
                         ON
                               person.per_id = vid_per.per_id
                         WHERE
                               per_name LIKE'%".$pName."%'   
                         ORDER BY 
                               vid_view DESC 
                         LIMIT 30";
   
           $db_access = new db_query($sql_query);
           $top_new_video = array();
           while ($row = mysql_fetch_assoc($db_access->result)) {
               $top_new_video[] = $row;
           }
           unset($db_access); 
        

        /* ======================== RESPONSE  ========================= */
        $response = new RequestResponse();
        $response->setBodyJSON(array("videos" => $top_new_video));
        $response->process();
   }
   /**
     * actionView
     * @todo Tra ve danh sach video theo ten bai hat
    */  
   public function actionSearch(){
      import("database");
      $max_result = 10;
      if(!isset($_GET['keyword'])){
         $reponse = new RequestResponse(400, "Missing 'keyword' arguments");
         $reponse->process();
      }else{
         $keyword = $_GET['keyword'];
      } 
      if(isset($_GET['page'])){
         $page = $_GET['page'];
      }else{
         $page = 1;
      }
      
      /*================== INSERT DATABASE ====================*/
         $myString = new string();
         $search_text = trim($keyword);
         //$search_text = $myString->removeInjection($search_text);
         $search_keyword = $myString->convertUTF8($search_text);
         $search_keyword = $myString->removeWhitespace($search_keyword);
         $sql_insert = "INSERT INTO
                              search(search_text,
                                     search_keyword,
                                     search_date)
                              VALUES('" . $search_text . "',
                                     '" . $search_keyword . "',
                                     " . time() . ") 
                              ON DUPLICATE KEY UPDATE
                                 search_count = search_count + 1,
                                 search_date =" . time();
         $db_insert = new db_execute($sql_insert);
         unset($db_insert); 
      $start_index = ($page == 1) ? $page : ($page - 1) * $max_result + 1;
      /* ========================  LIST VIDEOS  ====================== */
           $status_code   = 0;
           $message       = 'Hết dữ liệu'; 
           $top_new_video = array();
           // Search from my sever
           /**
           $word_count = str_word_count($keyword);            
           if($word_count < 4){
              $sql_select = "SELECT 
                                  video.vid_id as vid,
                                  vid_image as image,
                                  vid_name as title,
                                  vid_id_youtube as link,
                                  vid_view as view,
                                  vid_duration as duration
                            FROM  
                                  video
                            ";
               $sql_where =  " WHERE
                                     vid_active = 1 AND vid_name LIKE'%" . $keyword . "%'   
                               ORDER BY 
                                     vid_view DESC 
                               LIMIT " . self::MAX_TOP_VIDEOS_SIZE;
           }else{
               $min_point  = $word_count - 2;
               $sql_select = "SELECT 
                                  video.vid_id as vid,
                                  ROUND(MATCH(vid_name) AGAINST('" . $keyword . "' IN BOOLEAN MODE)) as point,
                                  vid_image as image,
                                  vid_name as title,
                                  vid_id_youtube as link,
                                  vid_view as view,
                                  vid_duration as duration
                            FROM  
                                  video
                            ";
               $sql_where =  " WHERE 
                                    vid_active = 1 AND MATCH(vid_name) AGAINST('" . $keyword . "' IN BOOLEAN MODE)
                               HAVING 
                                    point >= " . $min_point . "   
                               ORDER BY 
                                     point DESC, vid_view DESC
                               LIMIT 10 "; 
           }
           
           $sql_query = $sql_select . $sql_where; 
           $db_access = new db_query($sql_query);
           $top_new_video = array();
           while ($row = mysql_fetch_assoc($db_access->result)) {
               $top_new_video[] = $row;
               $from = 'MY SEVER';
           }
           mysql_free_result($db_access->result);
           */
           
           $top_new_video = getVideoFromApi($keyword,$start_index,$max_result);
           unset($db_access); 
        

        /* ======================== RESPONSE  ========================= */
        $response = new RequestResponse();
        $response->setBodyJSON(array("videos" => $top_new_video));
        $response->process();
        
        
   }

}
function getVideoFromApi($keyword,$start_index,$max_results = 10){
   $array_result = array();
   if($keyword != ''){
      $keyword .= ' karaoke';
      $keyword = urlencode($keyword);
      $link_api = "https://gdata.youtube.com/feeds/api/videos?q=".$keyword."&start-index=".$start_index."&max-results=".$max_results."&alt=json";
      if(get_http_response_code($link_api) != 200){
         return false;
      }
      $respone = json_decode(file_get_contents($link_api),true);
      if(isset($respone['feed']['entry'])){
         $array_vid = $respone['feed']['entry'];
         $i= 0;
         $array_item = array();
         foreach($array_vid as $value){
            $i++;
            $id = exportID($value['id']['$t']);
            $image = 'https://i.ytimg.com/vi/'.$id.'/0.jpg';
            $title = handelVidName($value['title']['$t']);
            $duration = formatDuraction($value['media$group']['yt$duration']['seconds']);
            $view = $value['yt$statistics']['viewCount'];
            $array_item[] = array(  'id' => $i,
                                    'image' => $image,
                                    'title' => $title,
                                    'link' => $id,
                                    'view' => $view,
                                    'duration' => $duration
                                    );
         }
         $array_result = $array_item;
      }
      return $array_result;
   }
}
function exportID($responeID){
   $id = '';
   $postion = strpos($responeID,'/videos/');
   if($postion){
      $id = substr($responeID,$postion + 8);
   }
   return $id;
}

/**
* Thay the mot so ky tu trong chuoi
* @param $string video name
* @return string replaced
*/
function handelVidName($string){
   $vidName = '';
   
   $mixsearch = array();
   $mixsearch[0] = 'karaoke';
   $mixsearch[1] = '';
   $mixsearch[2] = '_';
   $mixsearch[3] = '+';
   $mixsearch[4] = "'";
   $mixsearch[5] = "[";
   $mixsearch[6] = "]";
   $mixreplace = array();
   $mixreplace[0] = '';
   $mixreplace[1] = ' ';
   $mixreplace[2] = ' ';
   $mixreplace[3] = ' ';
   $mixreplace[4] = "\\'";
   $mixreplace[5] = ' ';
   $mixreplace[6] = ' ';
   
   $patterns = array();
   $patterns[0] = '/\([a-z0-9A-Z]+\)/';
   $patterns[1] = '/\[[a-z0-9A-Z]+\]/';
   $replacements = '';
   $replacements = array();
   $replacements[0] = '';
   $replacements[1] = '';
   $vidName = preg_replace($patterns, $replacements, $string);
   $vidName = str_ireplace($mixsearch,$mixreplace,$vidName);
   $vidName = trim($vidName);
   return $vidName;
}

/**
* Format duraction video
* @param $duraction kieu int
* @return string format 01:08:06
*/
function formatDuraction($duration){
   $formated = '00:00';
   if($duration == 0)
      return $formated;
   else{
      $hours = floor($duration/3600);
      $minutes = floor(($duration / 60) % 60);
      $seconds = $duration % 60;
      if($hours > 0){
         $hours = ($hours > 9) ? $hours . ':' : '0'.$hours . ':';
      }else{
         $hours = '';
      }
      if($minutes > 0){
         $minutes = ($minutes > 9) ? $minutes . ':' : '0'.$minutes . ':';
      }else{
         $hours = '00';
      }
      if($seconds > 0){
         $seconds = ($seconds > 9) ? $seconds : '0'.$seconds;
      }else{
         $seconds = '00';
      }
      $formated = $hours . $minutes .$seconds;
   }
   return $formated;
        
}

?>
